package com.school.fuyuan.common.util;

import cn.hutool.core.date.DateUtil;
import com.school.fuyuan.framework.config.config.RabbitConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zrhong
 * @version 1.0
 * @date 2019/3/28 23:41
 * @description
 */
@Component
public class InfoManageUtil {
    private final RabbitTemplate rabbitTemplate;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public InfoManageUtil(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public Date getApptDate(String appointment, int date, int hour, int minute, int second) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date appointmentDate = DateUtil.parse(appointment, "yyyy-MM-dd");
        //前一天的10点
        Calendar calendar = DateUtil.calendar(appointmentDate);
        calendar.add(calendar.DATE, date);
        calendar.add(calendar.HOUR, hour);
        calendar.add(calendar.MINUTE, minute);
        calendar.add(calendar.SECOND, second);
        Date returnDate = DateUtil.parse(formatter.format(calendar.getTime()), "yyyy-MM-dd HH:mm:ss");
        return returnDate;
    }

    public void sendApptMq(Date yesterday, int id, Date appointmentDate) {
        Date now = DateUtil.parse(DateUtil.now(), "yyyy-MM-dd HH:mm:ss");
        //预约时间需要比当前时间晚才发送队列
        if (now.before(yesterday)) {
            int time = (int) (yesterday.getTime() - now.getTime());
            // 添加延时队列
            this.rabbitTemplate.convertAndSend(RabbitConfig.PER_QUEUE_TTL_EXCHANGE_NAME, RabbitConfig.TTL_DELAY_ROUTING_KEY, id, message -> {
                // TODO 第一句是可要可不要,根据自己需要自行处理
//                message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, Integer.class.getName());
                message.getMessageProperties().setExpiration(time + "");
                return message;
            });
            logger.info("[发送时间] - [{}],[appointmentDate]-[{}],[yesterday]-[{}],[second]-[{}]", now, appointmentDate, yesterday, time);
        }
    }
}
